package com.janwen.j2ee.mail;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class JavaEmailServiceDemo {

	public static void sendEmail(String email_context) throws AddressException {

		try {
			Properties props = System.getProperties();
			props.setProperty("mail.smtp.host", EmailAuthInfo.EMAIL_HOST);
			props.setProperty("mail.smtp.auth", "true");

			Session session = Session.getDefaultInstance(props,
					new Authenticator() {
						@Override
						public PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(
									EmailAuthInfo.USER_NAME,
									EmailAuthInfo.PASS_WORD);
						}
					});
			session.setDebug(true);
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(EmailAuthInfo.EMAIL_FROM));
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(
					EmailAuthInfo.EMAIL_TO));
			message.setSubject("I'am email subject from sts", "utf-8");
			MimeMultipart mmp = new MimeMultipart();
			MimeBodyPart mbp_text = new MimeBodyPart();
			// "text/plain"是文本型，没有样式，
			// "text/html"是html样式，可以解析html标签
			mbp_text.setContent(email_context,
					"text/html;charset=gbk");
			mmp.addBodyPart(mbp_text); // 加入邮件正文
			message.setContent(mmp);
			Transport.send(message);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
